package com.example.socialmediaplatform.post;

import com.example.socialmediaplatform.model.Notification;
import com.example.socialmediaplatform.model.NotificationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/post")
public class PostController {
    @Autowired
    private PostJpaRepository postJpaRepository;

    @Autowired
    private PostLikeRepository postLikeRepository;

    @Autowired
    private NotificationRepository notificationRepository;

    // 发帖
    @PostMapping("/create")
    public ResponseEntity<?> createPost(Authentication authentication, @RequestBody PostDTO postDTO) {
        Post post = new Post();
        post.setUsername(authentication.getName());
        post.setDescription(postDTO.getDescription());
        post.setTargetDate(postDTO.getTargetDate());
        post.setImageUrls(postDTO.getImageUrls());
        post.setVideoUrls(postDTO.getVideoUrls());
        postJpaRepository.save(post);
        
        // 创建通知 - 通知所有用户有新帖子
        List<String> allUsers = postJpaRepository.findAll().stream()
            .map(Post::getUsername)
            .distinct()
            .filter(username -> !username.equals(authentication.getName()))
            .collect(Collectors.toList());
        
        for (String username : allUsers) {
            Notification notification = new Notification();
            notification.setType("newPost");
            notification.setContent(authentication.getName() + " 发布了新帖子");
            notification.setFromUser(authentication.getName());
            notification.setToUser(username);
            notification.setReaded(false);
            notification.setCreatedAt(new Date());
            notificationRepository.save(notification);
        }
        
        return ResponseEntity.ok("发帖成功");
    }

    // 分页获取所有帖子
    @GetMapping("/list")
    public ResponseEntity<?> listPosts() {
        List<Post> posts = postJpaRepository.findAll();
        List<PostDTO> dtos = posts.stream().map(this::toDTO).collect(Collectors.toList());
        return ResponseEntity.ok(dtos);
    }

    // 获取单个帖子详情
    @GetMapping("/{id}")
    public ResponseEntity<?> getPost(@PathVariable Long id) {
        Optional<Post> postOpt = postJpaRepository.findById(id);
        if (postOpt.isEmpty()) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(toDTO(postOpt.get()));
    }

    // 获取我的帖子
    @GetMapping("/my")
    public ResponseEntity<?> myPosts(Authentication authentication) {
        List<Post> posts = postJpaRepository.findByUsername(authentication.getName());
        List<PostDTO> dtos = posts.stream().map(this::toDTO).collect(Collectors.toList());
        return ResponseEntity.ok(dtos);
    }

    // 删除我的帖子
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deletePost(Authentication authentication, @PathVariable Long id) {
        Optional<Post> postOpt = postJpaRepository.findById(id);
        if (postOpt.isEmpty()) return ResponseEntity.notFound().build();
        Post post = postOpt.get();
        if (!post.getUsername().equals(authentication.getName())) {
            return ResponseEntity.status(403).body("无权删除他人帖子");
        }
        postJpaRepository.deleteById(id);
        return ResponseEntity.ok("删除成功");
    }

    // 评论帖子
    @PostMapping("/comment")
    public ResponseEntity<?> commentPost(Authentication authentication, @RequestBody CommentDTO commentDTO) {
        String username = authentication.getName();
        Optional<Post> postOpt = postJpaRepository.findById(commentDTO.getPostId());
        if (postOpt.isEmpty()) return ResponseEntity.notFound().build();
        Post post = postOpt.get();
        PostComment comment = new PostComment(username, commentDTO.getContent(), new java.util.Date());
        post.getComments().add(comment);
        postJpaRepository.save(post);
        
        // 返回评论DTO而不是实体
        PostCommentDTO commentResponseDTO = new PostCommentDTO(username, commentDTO.getContent(), new java.util.Date());
        return ResponseEntity.ok(commentResponseDTO);
    }

    private PostDTO toDTO(Post post) {
        PostDTO dto = new PostDTO();
        dto.setId(post.getId());
        dto.setUsername(post.getUsername());
        dto.setDescription(post.getDescription());
        dto.setTargetDate(post.getTargetDate());
        dto.setImageUrls(post.getImageUrls());
        dto.setVideoUrls(post.getVideoUrls());
        
        // 添加点赞数和评论数
        try {
            List<PostLike> likes = postLikeRepository.findByPostId(post.getId());
            dto.setLikes(likes.size());
            dto.setLikedUsers(likes.stream().map(PostLike::getUsername).collect(Collectors.toList()));
        } catch (Exception e) {
            dto.setLikes(0);
            dto.setLikedUsers(new java.util.ArrayList<>());
        }
        
        try {
            // 设置评论数量
            dto.setComments(post.getComments().size());
            
            // 设置评论内容数组
            List<PostCommentDTO> commentDTOs = post.getComments().stream()
                .map(comment -> new PostCommentDTO(
                    comment.getUsername(), 
                    comment.getDescription(), // PostComment中的字段名是description
                    comment.getTargetDate()   // PostComment中的字段名是targetDate
                ))
                .collect(Collectors.toList());
            dto.setCommentList(commentDTOs);
        } catch (Exception e) {
            dto.setComments(0);
            dto.setCommentList(new java.util.ArrayList<>());
        }
        
        return dto;
    }
}

// DTO 示例
class CommentDTO {
    private Long postId;
    private String content;
    public Long getPostId() { return postId; }
    public void setPostId(Long postId) { this.postId = postId; }
    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
} 
